// 所有的数据操作都由 Redux Toolkit 来完成
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { cartAPI } from "../../api"

// 异步获取全部购物车数据
export const fetchCart = createAsyncThunk(
    'cart/fetchCart',
    async (_, { dispatch }) => {
        const response = await cartAPI.getAll()
        // 返回的数据会作为 action.payload
        return response.data
    },
)

// 异步新增购物车商品
export const addProductToCart = createAsyncThunk(
    'cart/addProductToCart',
    // 添加商品时，传入商品信息，数量，规格
    async ({ product, quantity, selectedSpecs }, { dispatch }) => {
        // 先检查购物车中是否已有该商品
        const cartResponse = await cartAPI.getAll()
        console.log('cartResponse', cartResponse)
        // 找到已有商品 购物车商品商品的商品id 和 传入的商品id 相同，并且购物车商品的规格 和 传入的规格相同
        const existingCartItem = cartResponse.data.find(item => item.productId === product.id && JSON.stringify(item.selectedSpecs) === JSON.stringify(selectedSpecs))
        console.log('existingCartItem', existingCartItem)
        if (existingCartItem) {
            // 如果有，更新数量
            await cartAPI.update(existingCartItem.id, {
                ...existingCartItem,
                quantity: existingCartItem.quantity + quantity,
            })
        } else {
            // 如果不存在
            const newCartItem = {
                productId: product.id,
                name: product.name,
                price: product.price,
                image: product.image,
                quantity,
                selectedSpecs,
            }
            await cartAPI.add(newCartItem)
        }
        // 操作完成之后，重新获取购物车列表
        const updatedCartResponse = await cartAPI.getAll()
        return updatedCartResponse.data
    },
)

// 异步更新购物车商品数量

export const updateCartItem = createAsyncThunk(
    'cart/updateCartItem',
    // 给某个商品更新为多少数量  
    async ({ id, quantity }, { dispatch }) => {
        await cartAPI.update(id, { quantity })
        const response = await cartAPI.getAll()
        return response.data
    }
)


// 异步删除购物车商品


export const removeFromCart = createAsyncThunk(
    'cart/removeFromCart',
    async (id, { dispatch }) => {
        await cartAPI.delete(id)
        const response = await cartAPI.getAll()
        return response.data
    },
)

// 异步清空购物车

export const clearCart = createAsyncThunk(
    'cart/clearCart',
    async (_, { dispatch }) => {
        const response = await cartAPI.clear()
        // 返回的数据会作为 action.payload
        return []
    },
)



// 定义初始状态
const initialState = {
    cart: [],
    totalPrice: 0,
    error: null,
    // 加载状态（有异步） 不需要设置，因为使用的是 createAsyncThunk 的 pending, fulfilled, rejected
    loading: false,
}

// 生成 cart的 reducer 和 actions
const cartSlice = createSlice({
    name: "cart",
    initialState,
    reducers: {
        calculateTotalPrice(state) {
            state.totalPrice = state.cart.reduce((total, item) => {
                return total + item.price * item.quantity
            }, 0)
        }
    },
    // 异步的 处理逻辑
    extraReducers: (builder) => {
        builder
            .addCase(fetchCart.pending, (state) => {
                state.loading = true
            })
            .addCase(fetchCart.fulfilled, (state, action) => {
                state.loading = false
                state.cart = action.payload
            })
            .addCase(fetchCart.rejected, (state, action) => {
                state.loading = false
                state.error = action.error.message
            })
            .addCase(addProductToCart.fulfilled, (state, action) => {
                state.cart = action.payload
            })
            .addCase(clearCart.fulfilled, (state, action) => {
                state.cart = action.payload
            })
            .addCase(removeFromCart.fulfilled, (state, action) => {
                state.cart = action.payload
            })
            .addCase(updateCartItem.fulfilled, (state, action) => {
                state.cart = action.payload
            })
    }

})
export const { calculateTotalPrice } = cartSlice.actions
export default cartSlice.reducer